import Express, { Application, Request, Response, NextFunction } from "express";
import fs from "fs";
import path from "path";
import glob from "glob";
import Charset from "superagent-charset";
import Superagent, { ResponseError, Response as AgentResponse} from "superagent";
interface BootOption {

}
function globSync(dir: string): Promise<string[]> {
    return new Promise((resolve, reject) => {
        glob(dir, function(er, files) {
            if (er) {
                reject(er);
            } else {
                resolve(files);
            }
        });
    });
}
export default async function(app: Application, options: BootOption) {
    const files = await globSync(path.resolve(__dirname, "./conf/*.json"));
    const confObjs: Record<string, any> = {};
    files.forEach((vo: string) => {       
        const confObj = require(vo);
        Object.assign(confObjs, confObj);
    });
    app.use(function(req: Request, res: Response, next: NextFunction) {
        let pathArrs = req.path.split("/").slice(1);

        const pathKey = `/${pathArrs[0]}`;
        console.log("path obj==>", confObjs[pathKey])
        if (confObjs[pathKey]) {
            const confObj = confObjs[pathKey];
            if (confObj.overwrite) {
                pathArrs = pathArrs.slice(1);
            }
            const request = Charset(Superagent);
            const url = confObj.proxy + "/" + pathArrs.join("/");
            const agentReq = request.get(url)
                .query(req.query)
                .set("Accept", "*/*")
                .set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.3538.400 QQBrowser/9.7.12954.400")
                .set("Accept-Language", "zh-CN");
            if (confObj.headers) {
                for (let key in confObj.headers) {
                    agentReq.set(key, confObj.headers[key]);
                }
            }
            agentReq.buffer(true)
                .charset("utf-8")
                .end((err: ResponseError, response: AgentResponse) => {
                    if (err) {
                        console.log("agent error", err);
                    } else {
                        // if (response.header) {
                        //     for (let key in response.header) {
                        //         res.set(key, response.header[key]);
                        //     }
                        // }
                        console.log("response==>", response);
                        res.send(response.text);
                    }
                })
        } else {
            next();
        }
    });
    const dir = path.join(__dirname, "controllers");
    fs.readdirSync(dir).forEach((name: string) => {
        const file = path.join(dir, name);
        if (fs.statSync(file).isDirectory()) return;
        const obj = require(file);
        const fileName = obj.name || name;
        const prefix = obj.prefix || "";
        let handler: Function;
        let method: string;
        let url: string;
        // if (obj.engine) app.set("view engine", obj.engine);
        // app.set("views", path.join(__dirname, "controllers", name, "views"));
        for (let key in obj) {
            if (["get", "put", "post", "delete"].includes(key)) {
                method = key;
                const handlers = obj[key];
                for (let name in handlers) {
                    handler = handlers[name];
                    url = `${prefix}/${name}`;
                    console.log("url===>", url);
                    (app as any)[method](url, handler);
                }
            }
        }
    });
}